/*
 * Copyright 2008-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.appengine.twitter.infrastructure.persistent.jpa;


import java.util.List;

import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.google.appengine.twitter.domain.model.User;
import com.google.appengine.twitter.domain.model.UserRepository;

/**
 *
 * @author politics wang
 * @since Apr 23, 2009
 *
 */
public class JpaUserRepository extends JpaSupport implements UserRepository {
	
	@Override
	@Transactional
	public void save(User user) {
		jpaTemplate.persist(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAll() {
		return emf.createEntityManager().createQuery("select u from " + User.class.getName() + " u").getResultList();
	}

	@Override
	public User findByEmailOrUsername(String principal) {
		return new PrincipalQuery().candicates(new String[] {"email", "username"}).principal(principal).query();
	}
	
	private class PrincipalQuery {

		private String[] candicates;
		private String principal;

		public PrincipalQuery candicates(String[] candicates) {
			this.candicates = candicates;
			return this;
		}

		public PrincipalQuery principal(String principal) {
			this.principal = principal;
			return this;
		}

		public User query() {
			for (String candicate : candicates) {
				User user = tryCandicate(candicate);
				if (user != null) {
					return user;
				}
			}
			
			return null;
		}

		@SuppressWarnings("unchecked")
		private User tryCandicate(String candicate) {
			Query emailQuery = emf.createEntityManager().createQuery("select u from " + User.class.getName() + " u where u." + candicate + " = :principal");
			emailQuery.setParameter("principal", principal);
			List<User> resultList = emailQuery.getResultList();
			return CollectionUtils.isEmpty(resultList) ? null : resultList.iterator().next();
		}
		
	}

}
